<template>
    <div class="detail">
        <van-nav-bar
            title="商品交易记录"
            right-text="新增"
            left-arrow
            @click-left="$router.go(-1)"
            @click-right="showPopup = true;operateType = '新增'"
            fixed
            placeholder
        />
        <div class="overview">
            <div class="name">名称：<span>{{ baseInfo.name || '-' }}</span></div>
            <div class="bianhao">编号：<span>{{ baseInfo.code || '-' }}</span></div>
            <div class="type">款式：<span>{{ baseInfo.type == 1 ? '样衣' : baseInfo.type == 2 ? '商品' : '-' }}</span></div>
            <div class="merchant" style="white-space: nowrap;">商家：<span>{{ baseInfo.storeName  || '-' }}</span></div>
            <div class="total-num">总数量：<span>{{ sumNum || '-' }}</span></div>
            <div class="total-price price">总价格：<span>{{ sumPrice || '-' }}</span></div>
        </div>
        
        <div class="history-box">
            <div class="record-header">
                <van-swipe-cell>
                    <div class="header-ctn">
                        <div class="header-item time">时间</div>
                        <div class="header-item num">数量</div>
                        <div class="header-item store-type">类型</div>
                        <div class="header-item price">单价(元)</div>
                        <div class="header-item total-price">总价(元)</div>
                    </div>
                </van-swipe-cell>
            </div>
            <div class="record-item" v-for="(item, index) in details" :key="index + 'record'">
                <van-swipe-cell>
                    <div class="record-ctn">
                        <div class="record-attr time">{{ new Date(item.updateTime).format('yyyyMMdd hh:mm:ss') }}</div>
                        <div class="record-attr num blue">{{ item.amount }}</div>
                        <div class="record-attr store-type">
                            <span v-if="item.creaseType == '1'" class="green">出库</span>
                            <span v-if="item.creaseType == '2'" class="red">入库</span>
                        </div>
                        <div class="record-attr price">￥{{ item.price }}</div>
                        <div class="record-attr total-price red">
                            <span v-if="item.creaseType == '1'" class="green">{{item.priceTotal}}</span>
                            <span v-if="item.creaseType == '2'" class="red">-{{item.priceTotal}}</span>
                        </div>
                    </div>
                    <template #right>
                        <div class="btn-box">
                            <van-button square type="danger" size="small" text="删除" @click="delHandle(item.id)" />
                            <van-button square type="default" size="small" text="编辑" @click="editHandle(item)" />
                        </div>
                    </template>
                </van-swipe-cell>
            </div>
            <div v-if="details.length === 0" class="nodata">暂无交易记录</div>
        </div>
        
        <van-popup
            v-model="showPopup"
            position="bottom"
            style="height: 64%; padding: .2rem .2rem 0.1rem;"
            round
            closeable
        >
            <div class="top-ctn">
                <van-image
                    width="100"
                    height="100"
                    :src="imgUrl + baseInfo.photoUrl"
                />
                <div class="base-info">
                    {{ baseInfo.name || '-' }}
                    <br>
                    {{ baseInfo.code || '-' }}#{{ baseInfo.type == 1 ? '样衣' : baseInfo.type == 2 ? '商品' : '-' }}
                    <br>
                    <div style="padding-top: .2rem;">{{ baseInfo.storeName }}</div>
                </div>
            </div>
            <van-form @submit="onSubmit">
                <van-field name="storeType" label="库存类型">
                    <template #input>
                        <van-radio-group v-model="tradeInfo.creaseType" direction="horizontal">
                            <van-radio name="1">出库</van-radio>
                            <van-radio name="2">入库</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
                <van-field
                    type="number"
                    label="单价"
                    name="单价"
                >
                    <template #input>
                        <van-stepper v-model="tradeInfo.price" min="0" decimal-length="2" />（元）
                    </template>
                </van-field>
                <van-field
                    type="number"
                    label="数量"
                    name="数量"
                >
                    <template #input>
                        <van-stepper v-model="tradeInfo.amount" />
                    </template>
                </van-field>
                <van-field
                    type="number"
                    label="总价格"
                    name="总价格"
                    readonly
                >
                    <template #input>
                        <span style="color: red;">￥{{ totalPrice }}</span>
                    </template>
                </van-field>
                <van-field
                    v-model="tradeInfo.sendTime"
                    type="input"
                    label="操作时间"
                    name="操作时间"
                    autocomplete="off"
                    @click="showDateTimePicker = true"
                    readonly
                />
                <div style="margin: 16px;">
                    <van-button round block type="info" native-type="submit">提交</van-button>
                </div>
            </van-form>
        </van-popup>
        <van-popup v-model="showDateTimePicker" position="bottom">
            <van-datetime-picker v-model="sendTime" type="datetime" @cancel="showDateTimePicker = false" @confirm="onConfirm"/>
        </van-popup>
    </div>
</template>

<script>
    import $axios from '@/assets/js/$axios.js';
    import { getCookie } from '@/assets/js/cookieOpt.js';
    import config from '@/view/config_img_url.js';

    export default {
        data() {
            return {
                imgUrl: config.imgUrl,
                goodId: -1,
                showPopup: false,
                showDateTimePicker: false,
                sendTime: new Date(),
                sumNum: '',
                sumPrice: '',
                baseInfo: {
                    name: '',
                    code: '',
                    type: '',
                    photoUrl: '',
                    store: '',
                    storeName: '',
                },
                tradeInfo: {
                    id: -1,
                    creaseType: '', // 库存类型 1：出库   2：入库
                    price: '',
                    amount: 0,
                    sendTime: ''
                },
                details: [],
                operateType: ''
            }
        },
        computed: {
            totalPrice: function () {
                return this.tradeInfo.price * this.tradeInfo.amount;
            },
            onSubmit() {
                if (this.operateType === '新增') {
                    return this.addHandle;
                } else if (this.operateType === '编辑') {
                    return this.sendEditQuery;
                }
                return (function () {});
            }
        },
        created() {
            this.goodId = this.$route.params.id;
            
            if (this.goodId) {
                this.getDetail(this.goodId);
            } else {
                this.$toast('无效的商品ID')
            }
        },
        methods: {
            getDetail(goodId) {
                $axios.post2('/complain_test/api/goods/getDetail', {
                    goodId,
                    accessToken: getCookie('token')
                }).then(res => {
                    // console.log('getDetail', res);
                    if (res.code === 200) {
                        let data = res.data;
                        
                        this.baseInfo.name = data.name;
                        this.baseInfo.code = data.code;
                        this.baseInfo.type = data.type;
                        this.baseInfo.photoUrl = data.photoUrl; // todo，这个也要返回
                        this.baseInfo.store = data.store;
                        this.baseInfo.storeName = data.storeName;
                        
                        this.sumNum = data.amount;
                        this.sumPrice = data.totalPrice;
                        this.details.splice(0);
                        this.details.push(...data.details);
                    }
                })
            },
            addHandle() {
                let tradeInfo = this.tradeInfo; // 这个里有id，下面传参用不到
                
                $axios.post('/complain_test/api/goods/saveDetailInfo', {
                    ...this.baseInfo,
                    "amount": tradeInfo.amount,
                    "creaseType": tradeInfo.creaseType,
                    "price": tradeInfo.price,
                    "sendTime": tradeInfo.sendTime,
                }).then(res => {
                    // console.log('新增商品交易记录', res);
                    if (res.code === 200) {
                        this.$toast(res.msg);
                        this.showPopup = false;
                        this.getDetail(this.goodId);
                    }
                })
            },
            onConfirm() {
                this.tradeInfo.sendTime = new Date(this.sendTime).format('yyyy-MM-dd hh:mm:ss');
                this.showDateTimePicker = false;
            },
            delHandle(id) {
                if (!id) return this.$toast('非法交易记录id');
                this.$dialog.confirm({
                    title: '提示',
                    message: '确定删除该条记录吗？'
                }).then(() => {
                        $axios.post2('/complain_test/api/goods/deleteDetail', {
                            id,
                            accessToken: getCookie('token')
                        }).then(res => {
                            // console.log('delHandle', res);
                            if (res.code === 200) {
                                this.$toast(res.msg);
                                this.getDetail(this.goodId);
                            }
                        })
                })
            },
            sendEditQuery() {
                $axios.post('/complain_test/api/goods/updateDetail', {
                    ...this.baseInfo,
                    ...this.tradeInfo
                }).then(res => {
                    if (res.code === 200) {
                        this.$toast(res.msg);
                        this.showPopup = false;
                        this.getDetail(this.goodId);
                    }
                })
            },
            editHandle(prod) {
                this.operateType = '编辑';
                this.showPopup = true;
                this.tradeInfo = {
                    id: prod.id,
                    creaseType: prod.creaseType,
                    price: prod.price,
                    amount: prod.amount,
                    sendTime: '',
                };
            }
        },
        watch: {
            showPopup(newVal) {
                if (newVal === false) {
                    this.tradeInfo = {
                        creaseType: '',
                        price: '',
                        amount: 0,
                        sendTime: ''
                    };
                }
            }
        },
    }
</script>

<style lang="less" scoped>
    /deep/ .van-stepper__input {
        width: 1.8rem;
        font-size: .32rem;
    }
    
    .red {
        color: #f12626;
    }
    .blue {
        color: #4747cf;
    }
    .green {
        color: green;
    }
    
    .detail {
        width: 100vw;
        min-height: 100vh;
        background-color: #f3f5f7;
    }
    
    .overview {
        width: 100%;
        padding: 0.4rem;
        background-color: #fff;
        font-weight: bold;
        font-size: .26rem;
        display: grid;
        grid-template-columns: repeat(2, 45%);
        grid-template-rows: repeat(2, .6rem);
        grid-column-gap: 9.6%;
        grid-row-gap: .1rem;
        align-items: center;
        
        span {
            font-size: .28rem;
            font-weight: bolder;
        }
    }
    
    .history-box {
        margin-top: .38rem;
        font-size: .3rem;
        white-space: nowrap;
        
        &>div {
            background-color: #fff;
        }
    }
    
    .header-ctn {
        font-weight: bold;
    }
    
    .record-item {
        height: .8rem;
        margin-top: .06rem;
        line-height: .8rem;
    }
    
    .header-ctn, .record-ctn {
        height: .8rem;
        display: flex;
        align-items: center;
        
        .time {
            width: 42%;
            padding-left: .1rem;
        }
        
        .num {
            width: 14%;
        }
        
        .store-type {
            width: 14%;
        }
        
        .price {
            width: 16%;
        }
        
        .total-price {
            width: 24%;
        }
    }
    
    .btn-box {
        height: 100%;
        display: flex;
        align-items: center
    }
    
    .top-ctn {
        display: flex;
        
        .base-info {
            margin-left: .2rem;
            font-size: .32rem;
            padding-top: 0.14rem;
            font-weight: bold;
        }
    }
    
    .nodata {
        height: 2rem;
        line-height: 2rem;
        text-align: center;
        color: #ccc;
    }
</style>

